var id=document.getElementById('Id').textContent;
var saveButton = document.getElementById('Sbutton');
var peifang1=document.getElementById('peifang1');
var jsonData=null;
saveButton.addEventListener('click', ()=> {

    var jingfangming = document.getElementById('jingfangming').value;
    if(jingfangming=="")
        jingfangming=null;
    var laiyuan = document.getElementById('laiyuan').value;
    if(laiyuan=="")
        laiyuan=null;
    var leixing = document.getElementById('leixing').value;
    if(leixing=="")
        leixing=null;
    var jixing = document.getElementById('jixing').value;
    if(jixing=="")
        jixing=null;
    var fanglun = document.getElementById('fanglun').value;
    if(fanglun=="")
        fanglun=null;
    var yongfayongliang = document.getElementById('yongfayongliang').value;
    if(yongfayongliang=="")
        yongfayongliang=null;
    var radio = document.getElementsByName('peifang3');
    for (i=0; i<radio.length; i++) {
        if (radio[i].checked) {
            var jinguzhi=radio[i].value
        }
    }
    var fangjimingyi = document.getElementById('fangjimingyi').value;
    if(fangjimingyi=="")
        fangjimingyi=null;
    var chaodai = document.getElementById('chaodai').value;
    if(chaodai=="")
        chaodai=null;
    var liupai = document.getElementById('liupai').value;
    if(liupai=="")
        liupai=null;
    var gongneng = document.getElementById('gongneng').value;
    if(gongneng=="")
        gongneng=null;
    var zhuzhi = document.getElementById('zhuzhi').value;
    if(zhuzhi=="")
        zhuzhi=null;
    var zhuzhizhengzhuang = document.getElementById('zhuzhizhengzhuang').value;
    if(zhuzhizhengzhuang=="")
        zhuzhizhengzhuang=null;
    var jinji = document.getElementById('jinji').value;
    if(jinji=="")
        jinji=null;
    // 创建要发送的数据对象
    var data = {
        id: id,
        jingfangming: jingfangming,
        laiyuan: laiyuan,
        leixing: leixing,
        jixing: jixing,
        fanglun: fanglun,
        yongfayongliang: yongfayongliang,
        jinguzhi: jinguzhi,
        fangjimingyi: fangjimingyi,
        chaodai: chaodai,
        liupai: liupai,
        gongneng: gongneng,
        zhuzhi: zhuzhi,
        zhuzhizhengzhuang: zhuzhizhengzhuang,
        jinji: jinji
    };
    console.log(jinguzhi);
    var xhr = new XMLHttpRequest();
    xhr.open('PUT', '/fjgl/', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            // 请求完成并成功处理后的回调函数
            console.log('数据已成功发送至后端');
            alert("保存成功！");
            // window.location.href="/fjgl";
        }
    };
    xhr.send(JSON.stringify(data));
});
function start(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/fjgl/pf/'+id, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            dataSource = JSON.parse(xhr.responseText);
            data1 = JSON.parse(JSON.stringify(dataSource));
            console.log(data1);
            getZhongyao()
        }
    };
    xhr.send();
}
var data1=[];
start();

function getZhongyao() {
    var container = document.getElementById('divPeifang');
    if (data1) {
        console.log(data1[0].sort);
        var html = "";
        for(var j=0;j<data1.length;j++){
            for(var k=0;k+1<data1.length-j;k++){
                if(data1[k].sort>data1[k+1].sort){
                    var t=data1[k];
                    data1[k]=data1[k+1];
                    data1[k+1]=t;}
            }
        }
        for (var i = 0; i < data1.length; i++) {
            var item = data1[i];
            html += '<span class="fangjispan">' + item.yaowu + ' &nbsp; ' + item.yongliang + ' &nbsp; ' + item.cankaoyongliang + ' &nbsp; ' + ' <img src="/images/quxiao.png" alt="" class="quxiaopic" onclick="del(\'' + item.id + '\')"> </img>';
            if (i != 0) {
                html += '<img src="/images/up.png" class="quxiaopic" onclick="up(\'' + item.sort + '\')"><img>';
            }
            if (i != data1.length-1) {
                html += '<img src="/images/down.png" class="quxiaopic" onclick="down(\'' + item.sort + '\')"></img>';
            }
            html += '</span>';
        }
    }
    var spnumber=document.getElementById('spnumber');
    spnumber.innerHTML=data1.length;
    container.innerHTML = html;
}
function add() {
    // if (peifang1) {
    var exist = false;
    var peifang1=document.getElementById('peifang1').value;
    if(peifang1==""){
        alert("请输入药名");
        return;
    }
    else {
        var peifang2 = document.getElementById('peifang2').value;
        if (!isNaN(peifang2)&&peifang2!="") {
            peifang2 = peifang2 + "克";
        }
        var cankaoyongliang = document.getElementById('cankaoyongliang').value;
        if (!isNaN(cankaoyongliang)&&cankaoyongliang!="") {
            cankaoyongliang = cankaoyongliang+"克";
        }
        for (var i = 0; i < data1.length; i++) {
            if (data1[i].yaowu == peifang1) {
                var data={
                    id:data1[i].id,
                    jingfang:id,
                    yaowu:peifang1,
                    yongliang:peifang2,
                    cankaoyongliang:cankaoyongliang,
                }
                var xhr = new XMLHttpRequest();
                xhr.open('PUT', '/fjgl/pf1', true);
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        // 请求完成并成功处理后的回调函数
                        console.log('数据已成功发送至后端');
                        alert('修改成功');
                    }
                };
                xhr.send(JSON.stringify(data));
                exist = true;
                break;
            }
        }
        if (!exist) {
            var sort = 0;
            if (data1.length > 0) {
                sort = data1[data1.length - 1].sort+1;
            }
            var data={
                jingfang:id,
                yaowu:peifang1,
                yongliang:peifang2,
                cankaoyongliang:cankaoyongliang,
                sort:sort
            }
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/fjgl/pf/', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // 请求完成并成功处理后的回调函数
                    console.log('数据已成功发送至后端');
                    alert('添加成功');
                }
            };
            xhr.send(JSON.stringify(data));
        }
    }
    start();
    console.log(data1)
    getZhongyao();
}

function del(id) {
    var result=confirm("确认删除当前内容吗？");
    if(result){
        // 发送 DELETE 请求
        fetch('/fjgl/pf/'+id, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json' // 可根据实际情况设置请求头
            },
        })

    }
    start();
    console.log(data1)
    getZhongyao();
}
// 获取中药名
function getyaoming(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/fjgl/yaowu', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            jsonData = JSON.parse(xhr.responseText);
        }
    };
    xhr.send();
}
getyaoming();
// 在获取的中药名中搜索
function searchData() {
    var keyword = peifang1.value.trim().toUpperCase();
    var results = document.getElementById('searchResults');
    // 清空之前的查询结果
    results.innerHTML = '';
    // 遍历JSON数据，查找匹配的信息
    for (var i = 0; i < jsonData.length; i++) {
        var nameIndex=jsonData[i].yaoming;
        if(nameIndex==null)
            continue;
        var name=nameIndex.toUpperCase();
        if (name.includes(keyword)) {
            // console.log(name);
            // 创建li元素，并将匹配的信息添加到ul标签中
            var li = document.createElement('li');
            li.textContent = nameIndex;
            li.addEventListener('click', function() {
                // 点击查询结果时，将信息装配到input标签中
                peifang1.value = this.textContent;
                results.innerHTML = ''; // 清空查询结果
            });
            results.appendChild(li);
        }
    }
}
function addCheck(){
    // 检查按下的按键是否为回车键，回车键的keyCode是13
    if (event.keyCode === 13) {
        add();
    }
}
function shenhe(){
    var data = {
        id: id,
        shenhe: "通过",
        shr: "admin"
    };
    console.log(data);
    // 发送 POST 请求
    var xhr = new XMLHttpRequest();
    xhr.open('PUT', '/fjgl/'+"shenhe", true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            // 请求完成并成功处理后的回调函数
            alert("已审核！");
        }
    };
    xhr.send(JSON.stringify(data));
}
function up(sort) {
    for (var i = 0; i < data1.length; i++) {
        if (data1[i].sort == sort) {
            var p = data1[i].sort;
            var q = data1[i - 1].sort;
            var datap={
                id:data1[i].id,
                sort:q,
            }
            var xhr = new XMLHttpRequest();
            xhr.open('PUT', '/fjgl/pf2', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // 请求完成并成功处理后的回调函数
                    console.log('数据已成功发送至后端');
                }
            };
            xhr.send(JSON.stringify(datap));
            var dataq={
                id:data1[i-1].id,
                sort:p,
            }
            var xhr = new XMLHttpRequest();
            xhr.open('PUT', '/fjgl/pf2', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // 请求完成并成功处理后的回调函数
                    console.log('数据已成功发送至后端');
                }
            };
            xhr.send(JSON.stringify(dataq));
            break;
        }
    }
    start();
    console.log(data1)
    getZhongyao();
}
function down(sort) {
    for (var i = 0; i < data1.length; i++) {
        if (data1[i].sort == sort) {
            var p = data1[i].sort;
            var q = data1[i + 1].sort;
            var datap={
                id:data1[i].id,
                sort:q,
            }
            var xhr = new XMLHttpRequest();
            xhr.open('PUT', '/fjgl/pf2', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // 请求完成并成功处理后的回调函数
                    console.log('数据已成功发送至后端');

                }
            };
            xhr.send(JSON.stringify(datap));
            var dataq={
                id:data1[i+1].id,
                sort:p,
            }
            var xhr = new XMLHttpRequest();
            xhr.open('PUT', '/fjgl/pf2', true);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    // 请求完成并成功处理后的回调函数
                    console.log('数据已成功发送至后端');

                }
            };
            xhr.send(JSON.stringify(dataq));
            break;
        }
    }
    start();
    console.log(data1)
    getZhongyao();
}